<?php

namespace HuangYi\LaravelAliyunOss;

use HuangYi\FlysystemAliyunOss\AliyunOssAdapter;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use OSS\OssClient;

class AliyunOssServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $oss = $this->app['config']->get('filesystems.disks.oss', []);
        $defaults = require __DIR__.'/../config/oss.php';

        $this->app['config']->set('filesystems.disks.oss', array_merge($defaults, $oss));
    }

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app['filesystem']->extend('oss', function ($app, $config) {
            $accessKeyId = $config['access_key_id'];
            $accessKeySecret = $config['access_key_secret'];
            $endpoint = $config['internal'] ?: $config['endpoint'];

            $oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $adapter = new AliyunOssAdapter($oss, $config['bucket'], $config['prefix']);
            $filesystem = new Filesystem($adapter);

            return $filesystem;
        });
    }
}
